layui.use('form', function() {
    var form = layui.form;

    // 表单验证
    form.verify({
        required: function(value) {
            if (!value) {
                return '该字段为必填项';
            }
        }
    });
});

// 加载所有学生信息
function loadStudents() {
    $.ajax({
        url: '/students/ajax',
        method: 'GET',
        success: function (data) {
            let content = '';
            data.forEach(student => {
                content += `
                    <tr>
                        <td>${student.id}</td>
                        <td>${student.studentNumber}</td>
                        <td>${student.name}</td>
                        <td>${student.age}</td>
                        <td>${student.major}</td>
                        <td>
                            <button class="layui-btn layui-btn-xs" onclick="editStudent(${student.id})">编辑</button>
                            <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteStudent(${student.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            $('#student-body').html(content);
        }
    });
}

// 添加学生
function addStudent() {
    // 清空表单
    $('#student-id').val('');
    $('#studentNumber').val('');
    $('#studentName').val('');
    $('#studentAge').val('');
    $('#studentMajor').val('');
    // 显示弹窗
    layui.layer.open({
        type: 1,
        title: '添加学生',
        content: $('#student-form'),
        area: ['500px', '400px']
    });
}

// 编辑学生
function editStudent(id) {
    $.ajax({
        url: `/students/${id}`,
        method: 'GET',
        success: function (data) {
            $('#student-id').val(data.id);
            $('#studentNumber').val(data.studentNumber);
            $('#studentName').val(data.name);
            $('#studentAge').val(data.age);
            $('#studentMajor').val(data.major);
            // 显示弹窗
            layui.layer.open({
                type: 1,
                title: '编辑学生',
                content: $('#student-form'),
                area: ['500px', '400px']
            });
        }
    });
}

// 删除学生
function deleteStudent(id) {
    layui.layer.confirm('确认删除该学生吗?', {icon: 3, title: '提示'}, function(index) {
        $.ajax({
            url: `/students/${id}`,
            method: 'DELETE',
            success: function() {
                layui.layer.msg('删除成功');
                loadStudents();  // 刷新学生列表
            }
        });
        layui.layer.close(index);
    });
}

// 保存学生（添加或编辑）
function saveStudent() {
    const id = $('#student-id').val();
    const studentData = {
        studentNumber: $('#studentNumber').val(),
        name: $('#studentName').val(),
        age: $('#studentAge').val(),
        major: $('#studentMajor').val()
    };

    let url = '/students';
    let method = 'POST';

    if (id) {
        url = `/students/${id}`;
        method = 'PUT';
    }

    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',  // 设置 Content-Type 为 JSON
        data: JSON.stringify(studentData),  // 转换为 JSON 格式
        success: function() {
            layui.layer.msg('保存成功');
            layui.layer.closeAll(); // 关闭弹窗
            loadStudents();  // 刷新学生列表
        },
        error: function() {
            layui.layer.msg('保存失败');
        }
    });
}

// 按姓名查询学生
function searchStudents() {
    const name = $('#search-name').val();  // 获取输入框中的姓名
    if (!name) {
        layui.layer.msg('请输入姓名');
        return;
    }

    $.ajax({
        url: `/students/search?name=${name}`,  // 将name作为查询参数发送到后端
        method: 'GET',
        success: function(data) {
            let content = '';
            data.forEach(student => {
                content += `
                    <tr>
                        <td>${student.id}</td>
                        <td>${student.studentNumber}</td>
                        <td>${student.name}</td>
                        <td>${student.age}</td>
                        <td>${student.major}</td>
                        <td>
                            <button class="layui-btn layui-btn-xs" onclick="editStudent(${student.id})">编辑</button>
                            <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteStudent(${student.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            $('#student-body').html(content);
        },
        error: function() {
            layui.layer.msg('查询失败');
        }
    });
}

// 关闭表单
function closeForm() {
    layui.layer.closeAll();  // 关闭弹窗
}
